package com.qbccn.userservice.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qbccn.dto.CodeStatus;
import com.qbccn.dto.ResponseResult;
import com.qbccn.dto.ResponseResultPage;
import com.qbccn.userservice.domain.SsoMenu;
import com.qbccn.userservice.domain.SsoMenuUser;
import com.qbccn.userservice.domain.SsoRole;
import com.qbccn.userservice.domain.SsoRoleUser;
import com.qbccn.userservice.dto.AddMenuParam;
import com.qbccn.userservice.dto.Menus;
import com.qbccn.userservice.dto.UpdateMenuParam;
import com.qbccn.userservice.dto.UserListInfo;
import com.qbccn.userservice.mapper.SsoMenuMapper;
import com.qbccn.userservice.mapper.SsoMenuUserMapper;
import com.qbccn.userservice.mapper.SsoRoleMapper;
import com.qbccn.userservice.mapper.SsoRoleUserMapper;
import com.qbccn.userservice.mapper.SsoUserInfoMapper;
import com.qbccn.userservice.service.RedisService;
import com.qbccn.userservice.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * @author linke
 * @date 2020-03-09 下午 21:32
 * @description
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private SsoUserInfoMapper ssoUserInfoMapper;
    @Autowired
    private RedisService redisService;
    @Autowired
    private SsoMenuMapper ssoMenuMapper;
    @Autowired
    private SsoMenuUserMapper ssoMenuUserMapper;
    @Autowired
    private SsoRoleMapper ssoRoleMapper;
    @Autowired
    private SsoRoleUserMapper ssoRoleUserMapper;


    @Override
    public ResponseResultPage findList(String username, String systemCode, String comCode,
                                       Integer page, Integer size) {
        Page page1 = PageHelper.startPage(page, size);
        List<UserListInfo> userListInfo = ssoUserInfoMapper.findUsers(username, systemCode, comCode);
        PageInfo info = new PageInfo(page1.getResult());
        return new ResponseResultPage(CodeStatus.OK, page, size, info.getSize(), userListInfo);
    }

    @Override
    public ResponseResult getSystemMenus(String systemCode) {
        return new ResponseResult(CodeStatus.OK, ssoMenuMapper.getSystemMenus(systemCode));
    }

    @Override
    public ResponseResult addMenuParam(AddMenuParam addMenuParam) {
        List<SsoMenu> ms = ssoMenuMapper.getMenu(addMenuParam.getSystemCode(), addMenuParam.getParentId());
        for (SsoMenu m : ms) {
            if (m.getPath().equals(addMenuParam.getPath())) {
                return new ResponseResult(CodeStatus.OK, "添加失败！已经存在该路径：" + addMenuParam.getPath());
            }
        }
        SsoMenu menu = new SsoMenu();
        menu.setCreateTime(new Date());
        menu.setParentId(addMenuParam.getParentId());
        menu.setName(addMenuParam.getName());
        menu.setPath(addMenuParam.getPath());
        menu.setTitle(addMenuParam.getTitle());
        menu.setIcon(addMenuParam.getIcon());
        menu.setRedirect(addMenuParam.getRedirect());
        menu.setSystemCode(addMenuParam.getSystemCode());
        menu.setSortId(addMenuParam.getSortId());
        ssoMenuMapper.insertSelective(menu);
        return new ResponseResult(CodeStatus.OK, "success");
    }

    @Override
    public ResponseResultPage getRoleList(String systemCode, int page, int size) {
        Page page1 = PageHelper.startPage(page, size);
        List<SsoRole> res = ssoRoleMapper.getList(systemCode);
        PageInfo info = new PageInfo(page1.getResult());
        return new ResponseResultPage(CodeStatus.OK, page, size, info.getSize(), res);
    }

    @Override
    public ResponseResultPage getRoles(String systemCode, int userId) {
        return new ResponseResultPage(CodeStatus.OK, ssoRoleMapper.getRoles(systemCode, userId));
    }


    @Transactional //开启事务
    @Override
    public ResponseResult updateRoles(String systemCode, int userId, int[] roleIds, int[] status) {
        List<SsoRoleUser> roleUsers = ssoRoleUserMapper.get(userId);
        for (int s = 0; s < roleIds.length; s++) {
            int has = -1;
            for (int i = 0; i < roleUsers.size(); i++) {
                if (roleIds[s] == roleUsers.get(i).getRoleId().intValue()) {
                    has = roleUsers.get(i).getRoleId();
                    break;
                }
            }
            if (has != -1) {//存在则更新
                ssoRoleUserMapper.update(has, userId, status[s]);
            } else {//不存在则新增
                SsoRoleUser ssoRoleUser = new SsoRoleUser();
                ssoRoleUser.setStatus(status[s]);
                ssoRoleUser.setCreateTime(new Date());
                ssoRoleUser.setRoleId(roleIds[s]);
                ssoRoleUser.setUserId(userId);
                ssoRoleUserMapper.insertSelective(ssoRoleUser);
            }
        }
        return new ResponseResult(CodeStatus.OK, "修改成功！");
    }

    @Override
    public ResponseResult addRole(String systemCode, String roleName, String roleDesc) {
        if (ssoRoleMapper.hasRoleName(roleName, systemCode) != null) {
            return new ResponseResult(CodeStatus.FAIL, "新增失败！已经存在的角色名" + roleName);
        }
        SsoRole role = new SsoRole();
        role.setCreateTime(new Date());
        role.setRoleDesc(roleDesc);
        role.setSystemCode(systemCode);
        role.setRoleName(roleName);
        ssoRoleMapper.insertSelective(role);
        return new ResponseResult(CodeStatus.OK, "新增成功！");
    }

    @Override
    public ResponseResult updateRole(int id, String systemCode, String roleName, String roleDesc) {
        SsoRole role = ssoRoleMapper.hasRoleName(roleName, systemCode);
        if (role != null && role.getId().intValue() != id) {
            return new ResponseResult(CodeStatus.FAIL, "修改失败！已经存在的角色名" + roleName);
        }
        ssoRoleMapper.update(id, roleName, roleDesc);
        return new ResponseResult(CodeStatus.OK, "修改成功！");
    }

    @Override
    public ResponseResult getMenus(String systemCode, String username) {
        List<Menus> menus = ssoMenuMapper.getMenus(systemCode, username);
        return new ResponseResult(CodeStatus.OK, menus);
    }

    @Override
    public ResponseResult updateUserMenu(String systemCode, String username, int[] menuIds, int[] status, int[] parentIds) {
        List<SsoMenuUser> menuUsers = ssoMenuUserMapper.get(username);
        for (int s = 0; s < menuIds.length; s++) {
            int has = -1;
            for (int i = 0; i < menuUsers.size(); i++) {
                if (menuIds[s] == menuUsers.get(i).getMenuId().intValue()) {
                    has = menuUsers.get(i).getMenuId();
                    break;
                }
            }
            if (has != -1) {//存在则更新
                ssoMenuUserMapper.update(username, has, status[s]);
            } else {//不存在则新增
                SsoMenuUser ssoMenuUser = new SsoMenuUser();
                ssoMenuUser.setStatus(status[s]);
                ssoMenuUser.setCreateTime(new Date());
                ssoMenuUser.setMenuId(menuIds[s]);
                ssoMenuUser.setUsername(username);
                ssoMenuUserMapper.insertSelective(ssoMenuUser);
            }
        }
        // 判断是否清理到父节点
        if (parentIds.length > 0)
            for (int i = 0; i < parentIds.length; i++)
                ssoMenuUserMapper.clearNode(username, parentIds[i]);

        //清理redis的菜单缓存
        redisService.delete("menu:" + username);

        if (parentIds.length > 0)
            return new ResponseResult(CodeStatus.OK, "修改成功！涉及到父节点，已把其下字节点置为无效。");
        else
            return new ResponseResult(CodeStatus.OK, "修改成功！");
    }

    @Override
    public ResponseResult deleteMenu(String systemCode, int menuId) {
        ssoMenuMapper.deleteMenu(systemCode, menuId);
        return new ResponseResult(CodeStatus.OK, "删除成功！");
    }

    @Override
    public ResponseResult updateMenu(UpdateMenuParam menuParam) {
        int res = ssoMenuMapper.hasMenu(menuParam.getSystemCode(), menuParam.getId(),
                menuParam.getPath());
        if (res > 0) {
            return new ResponseResult(CodeStatus.FAIL, "修改失败！已经存在的Path路径，请换一个Path路径。");
        }
        ssoMenuMapper.update(menuParam);
        return new ResponseResult(CodeStatus.OK, "修改成功！");
    }
}
